<template>
  <h2>star wallet</h2>
  <div class="wrapper">
    <van-divider :style="{ color: 'orange', padding: '0 16px' }">
      选择账户
    </van-divider>
    <van-field v-model="fieldValue" is-link readonly label="账户" placeholder="选择账户" @click="showPicker = true" />
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
    </van-popup>

    <van-divider :style="{ color: 'orange', padding: '0 16px' }">
      账户信息
    </van-divider>
    <van-cell-group inset>
      <!-- 输入任意文本 -->
      <van-field v-model=addr label="地址" />
      <van-field v-model=pk label="私钥" />
      <van-field v-model=balance label="余额" />
    </van-cell-group>

    <van-divider :style="{ color: 'orange', padding: '0 16px' }">
      导入账户
    </van-divider>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="address" name="addr" label="地址" placeholder="请输入地址"
          :rules="[{ required: true, message: '请填写地址' }]" />
        <van-field v-model="privateKey" name="pk" label="私钥" placeholder="请输入私钥"
          :rules="[{ required: true, message: '请填写私钥' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          导入账户
        </van-button>
      </div>
    </van-form>

    <van-divider :style="{ color: 'orange', padding: '0 16px' }">
      发起交易
    </van-divider>
    <van-form @submit="txSubmit">
      <van-cell-group inset>
        <van-field v-model="targetAddr" name="targetAddr" label="目标地址" placeholder="请输入目标地址"
          :rules="[{ required: true, message: '请填写地址' }]" />
        <van-field v-model="amount" name="amount" label="金额" placeholder="请输入金额"
          :rules="[{ required: true, message: '请填写金额' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          发起交易
        </van-button>
      </div>
    </van-form>

  </div>
</template>


<script>
import { ref } from "vue"
import Web3 from 'web3';
import { showSuccessToast } from 'vant';

var web3 = new Web3("ws://localhost:8545");


export default {
  name: 'App',
  components: {

  },
  setup() {
    // 获取本地已导入的账户数据
    const accountArray = ref(JSON.parse(localStorage.getItem("accountArray")) || []);
    // 获取表格列数据
    const columns = ref(JSON.parse(localStorage.getItem("columns")) || []);
    const count = ref(accountArray.value.length);
    // 定义钱包变量
    const fieldValue = ref('');
    const showPicker = ref(false);
    const addr = ref('');
    const pk = ref('');
    const balance = ref('');
    // 定义收款人的信息
    const targetAddr = ref('');
    const amount = ref('');

    // 选择账户
    const onConfirm = ({ selectedOptions }) => {
      console.log("selectedOptions", selectedOptions)
      showPicker.value = false;
      fieldValue.value = selectedOptions[0].text;
      // 获取账户的公私钥
      const account = accountArray.value[selectedOptions[0].value];
      addr.value = account.addr;
      pk.value = account.pk;

      // 获取账户余额
      web3.eth.getBalance(addr.value).then((ret) => {
        balance.value = web3.utils.fromWei(ret, "ether") + " eth";
      });
    };

    const address = ref('');
    const privateKey = ref('');
    // 导入账户
    const onSubmit = (values) => {
      const { addr, pk } = values;
      const account = {
        addr,
        pk
      };
      accountArray.value.push(account);
      localStorage.setItem("accountArray", JSON.stringify(accountArray.value));

      const item = {
        text: `Account${count.value + 1}`,
        value: count.value
      }
      columns.value.push(item);
      localStorage.setItem("columns", JSON.stringify(columns.value));
      count.value++;

      showSuccessToast("导入成功");
      console.log('submit', values);
      console.log('12345');
      address.value = "";
      privateKey.value = "";
    };

    // 发起交易
    const txSubmit = async (values) => {
      console.log("values: ", values);
      console.log("values.account", values.amount);

      // 获取账户交易次数
      let nonce = await web3.eth.getTransactionCount(addr.value);
      // 获取预计转账gas费
      let gasPrice = await web3.eth.getGasPrice();

      const txParams = {
        nonce: web3.utils.toHex(nonce),
        gasPrice,
        gasLimit: web3.utils.toHex(21000),
        from: addr.value,
        to: values.targetAddr,
        value: web3.utils.toWei(values.amount, "ether"),
      };
      console.log("txparams", txParams);
      const receipt = await web3.eth.sendTransaction(txParams);
      console.log("Transaction receipt:", receipt);
      web3.eth.getBalance(addr.value).then(res => {
        balance.value = web3.utils.fromWei(res, "ether");
        showSuccessToast("交易成功");
      })
      targetAddr.value="";
      amount.value="";
    };



    return {
      columns,
      onConfirm,
      fieldValue,
      showPicker,

      address,
      privateKey,
      onSubmit,
      txSubmit,

      addr,
      pk,
      balance,
      accountArray,
      count,
      targetAddr,
      amount
    };
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 16px;
}

.wrapper {
  padding: 16px;
  word-break: break-all;
}

h2 {
  text-align: center;
  color: orange;
}

p {
  padding: 16px;
}
</style>
